package cn.xiaopengstack.infrastructure.persistent.strategy.notify;

import cn.xiaopengstack.domain.trade.model.entity.NotifyTaskEntity;
import cn.xiaopengstack.domain.trade.model.valobj.NotifyTypeEnum;
import cn.xiaopengstack.infrastructure.event.EventPublisher;
import cn.xiaopengstack.infrastructure.persistent.strategy.model.MqConfigVO;
import cn.xiaopengstack.infrastructure.persistent.strategy.model.NotifyPayloadVO;
import cn.xiaopengstack.types.config.NotifyConfig;
import cn.xiaopengstack.types.enums.ResponseCode;
import cn.xiaopengstack.types.event.NotifyEvent;
import cn.xiaopengstack.types.exception.AppException;
import cn.xiaopengstack.types.utils.SpringContextUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

/**
 * @author jiangyangang
 */
@Slf4j
public class MQNotifyStrategy extends AbstractNotifyStrategy<MqConfigVO> {

    public MQNotifyStrategy(String scene) {
        super(scene);
    }

    @Override
    public void executeNotice(NotifyStrategyFactory.DynamicContext dynamicContext) throws AppException {
        try {
            NotifyTaskEntity notifyTaskEntity = dynamicContext.getNotifyTaskEntity();
            String notifyPayload = notifyTaskEntity.getNotifyPayload();
            NotifyPayloadVO notifyPayloadVO = JSONObject.parseObject(notifyPayload, NotifyPayloadVO.class);
            NotifyEvent notifyEvent = new NotifyEvent(NotifyEvent.NotifyEventMessage.builder()
                    .teamId(notifyTaskEntity.getTeamId())
                    .outTradeNoList(notifyPayloadVO.getOutTradeNoList())
                    .build(),
                    notifyTaskEntity.getTeamId());

            EventPublisher eventPublisher = SpringContextUtil.getBean(EventPublisher.class);
            eventPublisher.publish(notifyEvent);
        } catch (Exception e) {
            throw new AppException(ResponseCode.SETTLEMENT_NOTIFY_FAIL);
        }
    }

    @Override
    public NotifyTypeEnum type() {
        return NotifyTypeEnum.MQ;
    }

    @Override
    public MqConfigVO getConfig() {
        NotifyConfig.NotifyConfigHandle notifyConfigHandle = SpringContextUtil.getBean(NotifyConfig.NotifyConfigHandle.class);
        String topic = notifyConfigHandle.getTopic(scene);
        return MqConfigVO.builder()
                .topic(topic)
                .build();
    }
}
